package my.framework.comm;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

/**
 * @author:雷淑娥
 * @Date:2024/12/14 13:52
 * version:1.0
 */
public class MybatisUtils {
    static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    static SqlSession sqlSession;

    /**
     * 获取SqlSession
     * @param autoCommit
     * @return
     */
    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }

    /**
     * 获取Mapper 代理类
     * @param clazz
     * @param autoCommit
     * @return
     * @param <T>
     */
    public static  <T> T getMapper(Class<T> clazz,boolean autoCommit) {
        sqlSession = getSqlSession(autoCommit);
        return sqlSession.getMapper(clazz);
    }

    /**
     * 关闭会话
     */
    public static void closeSqlSession() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}
